package cn.linstudy.base;

import cn.hutool.http.HttpUtil;
import com.google.common.base.Strings;
import io.vavr.Tuple;
import io.vavr.Tuple2;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class LocationUtils {

    private static final Logger logger = LoggerFactory.getLogger(LocationUtils.class);

    public static String url = "http://api.map.baidu.com/geocoder/v2/?location=%s,%s&output=json&ak=b1PCgopEFcvDNmM25SUqVAyZjMDavR0h";
    private static Pattern cityPattern = Pattern.compile("\"city\":\"([\\w\\W]+?)\"");
    private static Pattern districtPattern = Pattern.compile("\"district\":\"([\\w\\W]+?)\"");

    public static Tuple2<String, String> getCityByLocation(String longitude, String latitude){
        final String requestUrl = String.format(url, latitude, longitude);
        final String result = HttpUtil.get(requestUrl, 5000);
        logger.info("第三方城市定位接口url={}，res={}", requestUrl, result);
        if (Strings.isNullOrEmpty(result)) {
            return Tuple.of("", "");
        }
        final String cityName = getName(cityPattern, result);
        final String districtName = getName(districtPattern, result);
        // 返回的结果类似(深圳, 龙岗)，第一个为市，第二个为区
        return Tuple.of(cityName.replaceAll("市", ""), districtName.replaceAll("区", ""));
    }

    private static String getName(Pattern p, String str){
        final Matcher matcher = p.matcher(str);
        if (matcher.find()){
            return matcher.group(1);
        }
        return "";
    }

    public static void main(String[] args) {
        System.out.println(getCityByLocation("114.4139450000", "22.6410900000"));
        System.out.println("===================================================================");
        System.out.println(getCityByLocation("114.4139450000", "22.6410900000"));
    }



}
